package com.qfedu.service.impl;

import com.jayway.jsonpath.internal.function.text.Concatenate;
import com.qfedu.mapper.ContractorMapper;
import com.qfedu.model.Contractor;
import com.qfedu.page.PageResult;
import com.qfedu.page.QueryPageBean;
import com.qfedu.service.IContractorService;
import com.qfedu.service.IProjectService;
import com.qfedu.utils.UUIDUtils;
import com.qfedu.vo.ConProVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 概述:
 *
 * @Author: Tbh
 * @Date: 2022/6/28 10:59
 */

@Service
public class ContractorServiceImpl implements IContractorService {

    @Autowired
    private ContractorMapper contractorMapper;

    @Autowired
    private IProjectService projectService;

    @Override
    public PageResult findPage(QueryPageBean queryPage) {
        PageResult pageResult = new PageResult();
        Integer currentPage = queryPage.getCurrentPage();
        Integer pageSize = queryPage.getPageSize();
        List<Contractor> page = contractorMapper.findPage((currentPage - 1) * pageSize,pageSize);
        Long count = contractorMapper.count();
        pageResult.setTotal(count);
        pageResult.setRows(page);
        return pageResult;

    }

    @Override
    @Transactional
    public int addAndBind(String cname, int[] pids) {
        Contractor contractor = new Contractor();
        contractor.setCname(cname);
        contractor.setCid(UUIDUtils.uuid());
        contractor.setUpdatetime(new Date());
        int row = contractorMapper.add(contractor);
        projectService.bindCid(contractor.getCid(),pids);
        return row;
    }

    @Override
    public Contractor findByCid(String cid) {
        Contractor contractor = contractorMapper.findConByCid(cid);
        return contractor;
    }

    @Override
    @Transactional
    public int updateAndBind(ConProVO conProVO) {
        Contractor contractor = new Contractor();
        contractor.setCid(conProVO.getCid());
        contractor.setUpdatetime(new Date());
        contractor.setCname(conProVO.getCname());
        int row = contractorMapper.updateCon(contractor);
        //先清空
        //同时更新project的did
        projectService.deleteCid(conProVO.getCid());

        //绑定工程
        projectService.bindCid(conProVO.getCid(),conProVO.getPids());
        return row;
    }

    @Override
    public int deleteByCid(String cid) {
        int row = contractorMapper.deleteByCid(cid);
        projectService.deleteCid(cid);
        return row;
    }
}
